﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace Travelers.Core
{
    public  class Compilers
    {
        private string _code;
        private string _name;
        private string _loginUrl;
        private string _startUrl;
        private string _codeFile;

        public Compilers(string code,string name,string loginUrl,string startUrl,string codeFile)
        {
            this._code = code;
            this._name = name;
            this._loginUrl = loginUrl;
            this._startUrl = startUrl;
            if (!String.IsNullOrEmpty(codeFile))
            {
                this._codeFile = codeFile;
            }
            else
            {
                this._codeFile = "Traveler.cs";
            }
        }

        public void Run()
        {
            string path = Directory.GetCurrentDirectory() + "\\" + this._name;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.GenerateInMemory = false;
            cp.OutputAssembly = this._name + "\\" + this._name + ".exe";
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            string[] source =new string[1];
            string fileContent = File.ReadAllText(Directory.GetCurrentDirectory() + "\\Code\\" + this._codeFile);
            fileContent = fileContent.Replace("[loginUrl]", this._loginUrl);
            fileContent = fileContent.Replace("[startUrl]", this._startUrl);
            fileContent = fileContent.Replace("//[code]", this._code);
            source[0] = fileContent;
            CSharpCodeProvider ccp = new CSharpCodeProvider();
            CompilerResults cr = ccp.CompileAssemblyFromSource(cp,source);
            if (cr.Errors.HasErrors)
            {
                StringBuilder errorMsg = new StringBuilder();
                foreach (CompilerError err in cr.Errors)
                {
                    errorMsg.Append(err.ErrorText);
                }
                System.Diagnostics.Debug.WriteLine(errorMsg.ToString());
            }
            else
            {
                /*
                System.Reflection.Assembly ass = cr.CompiledAssembly;
                Travelers.Code.Traveler _Compiled = ass.CreateInstance("Traveler");
                System.Reflection.MethodInfo mi = _Compiled.GetType().GetMethod("");
                mi.Invoke(_Compiled, null);
                 */
                System.Diagnostics.Process.Start(path + "\\" + this._name + ".exe");
            }
        }
    }
}
